package org.example.review.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.pojo.entity.OperationLog;
import com.common.pojo.resp.ApprovalRecordRespDTO;
import com.common.result.Result;
import org.example.review.dto.OperationLogDTO;
import org.example.review.dto.OperationLogDTO;
import org.example.review.service.OperaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.logging.Logger;

@RestController
@RequestMapping("/opera")
public class OperaController {

    private static final Logger logger = Logger.getLogger(OperaController.class.getName());

    @Autowired
    private OperaService operaService;

    /**
     * 获取操作日志列表
     *
     * @param params 查询参数
     * @return 操作日志列表
     */
    @GetMapping("/list")
    public Result<IPage<OperationLogDTO>> getOperationLogs(@RequestParam Map<String, Object> params) {
        logger.info("接收到获取操作日志列表请求，参数: " + params);
        try {
            int page = Integer.parseInt(params.getOrDefault("page", "1").toString());
            int size = Integer.parseInt(params.getOrDefault("size", "10").toString());

            Page<OperationLogDTO> pageParam = new Page<>(page, size);
            IPage<OperationLogDTO> result = operaService.getOperationLogs(pageParam);

            return Result.success(result);
        } catch (Exception e) {
            logger.severe("获取操作日志列表失败: " + e.getMessage());
            return Result.error("获取操作日志列表失败: " + e.getMessage());
        }
    }






    @PostMapping("/insert")
    public Result<String> insertOperationLog(@RequestBody OperationLogDTO operationLog) {
        // 快速校验
        if (operationLog == null || operationLog.getApplyid() == null || operationLog.getAction() == null) {
            return Result.error("关键参数 (applyid, action) 不能为空");
        }

        boolean success = operaService.insertOperationLog(operationLog);

        if (success) {
            return Result.success("操作日志记录成功");
        } else {
            return Result.error("操作日志记录失败，可能是未知操作类型");
        }
    }
    
    /**
     * 根据申请ID获取审核记录（供其他服务调用）
     * @param applyId 申请ID（Apply表的主键ID）
     * @return 审核记录列表
     */
    @GetMapping("/approval-records/{applyId}")
    public List<ApprovalRecordRespDTO> getApprovalRecords(@PathVariable Integer applyId) {
        logger.info("接收到获取审核记录请求，applyId: " + applyId);
        return operaService.getApprovalRecordsByApplyId(applyId);
    }
}
